package com.situ.shoplook.admin.api;

import com.situ.shoplook.common.model.Category;
import com.situ.shoplook.common.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/v1/categories", produces = "application/json;charset=utf-8")
public class CategoryApi {
    private CategoryService categoryService;

    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    //查询全部
    @GetMapping
    public Map<String, Object> findAll() {
        List<Category> categories = this.categoryService.findAll();
        return Map.of("data", categories, "code", 0);
    }

    /**
     * 查询类别树
     *
     * @return 类别树
     */
    @GetMapping("/tree")
    public Map<String, Object> findTree() {
        Category category = this.categoryService.findTree();
        return Map.of("data", category, "code", 0);
    }

    @GetMapping("/id/{id}")
    public Map<String, Object> findById(@PathVariable Integer id) {
        Category category = this.categoryService.findById(id);
        if (category == null) {
            return Map.of("code", false, "error", "查询的类别不存在");
        }
        return Map.of("data", category, "code", 0);
    }

    @PostMapping
    public Map<String, Object> save(@RequestBody Category category) {
        if (!StringUtils.hasText(category.getName())) {
            return Map.of("code", -1, "error", "类别名称不可为空");
        }

        boolean code = this.categoryService.save(category);
        return Map.of("code", code? 0: -1);
    }

    @PutMapping
    public Map<String, Object> update(@RequestBody Category category) {
        boolean code = this.categoryService.update(category);
        return Map.of("code", code? 0: -1);
    }

    @DeleteMapping
    public Map<String, Object> deleteByIds(@RequestBody Integer[] ids) {
        try {
            int rows = this.categoryService.deleteByIds(ids);
            return Map.of("data", rows, "code",  0);
        }catch (RuntimeException e){
            return Map.of("code", -1, "msg", e.getMessage());
        }
    }
}
